<?php

namespace App\Services\TakeBrokerageToBalance;

use App\Models\User;
use App\Models\Brokerage;
use Illuminate\Support\Facades\DB;

class TakeBrokerageToBalance
{
    protected User $user;
    protected Brokerage $brokerage;

    public function __construct(User $user, Brokerage $brokerage)
    {
        $this->user = $user;
        $this->brokerage = $brokerage;
    }

    protected function take()
    {
        DB::transaction(function () {
            $money = $this->user->dividend_brokerage;

            $userMoneyWillBe = big_decimal($money)->plus($this->brokerage->money);
            $this->user->update(['dividend_brokerage'=> $userMoneyWillBe]);
            $this->brokerage->update(['is_taken'=> true]);
            account_balances($this->user)->plusTakeBalance($this->brokerage->money);
        });
    }

    public function apply()
    {
        $this->take();
    }
}
